<template>
  <c-modal
    v-model="updateVisible"
    :title="title"
    :width="600"
    @cancel="updateCancel"
    destroyOnClose
  >
    <c-form
      v-model="updateForm"
      ref="updateForm"
      :rules="updateFormRules"
      :data="updateFormData"
    >
      <template v-slot:shortName="{ change }">
        <ul class="shortNameList">
          <li v-for="(item, idx) in updateForm.shortNames" :key="idx">
            <a-input
              class="inline-b"
              placeholder="请输入仓库简称"
              v-model.trim="updateForm.shortNames[idx].value"
              @change="change('shortName')"
            ></a-input>
            <c-button
              type="primary"
              shape="circle"
              class="inline-b"
              @click="addShortName"
              size="small"
              v-if="idx === 0"
            >
              <a-icon type="plus"></a-icon>
            </c-button>
            <c-button
              type="danger"
              shape="circle"
              class="inline-b"
              @click="delShortName(idx)"
              size="small"
              v-else
            >
              <a-icon type="minus"></a-icon>
            </c-button>
          </li>
        </ul>
      </template>
      <template v-slot:category>
        <ul class="categoryList" ref="categoryList">
          <li v-for="(item, idx) in updateForm.categoryFees" :key="idx">
            <c-category
              v-model.trim="updateForm.categoryFees[idx].categoryId"
              :class="validateCorrelationCategory(idx, 'categoryId')"
            ></c-category>
            <span>转货权费用：</span>
            <a-input
              class="fee"
              suffix="元/吨"
              v-model.trim="updateForm.categoryFees[idx].fee"
              :class="validateCorrelationCategory(idx, 'fee')"
            ></a-input>
            <c-button
              type="primary"
              shape="circle"
              @click="addCategory"
              size="small"
              v-if="idx === 0"
            >
              <a-icon type="plus"></a-icon>
            </c-button>
            <c-button
              type="danger"
              shape="circle"
              @click="delCategory(idx)"
              size="small"
              v-else
            >
              <a-icon type="minus"></a-icon>
            </c-button>
          </li>
        </ul>
      </template>
      <template v-slot:city>
        <c-city v-model="updateForm.city"></c-city>
      </template>
    </c-form>
    <template v-slot:footer>
      <div class="tc">
        <c-button type="primary" width="200px" height="40px" @click="submit"
          >确认提交</c-button
        >
      </div>
    </template>
  </c-modal>
</template>

<script>
import { addwarehouse } from "@/api/warehouse";

const updateFormData = [
  {
    label: "仓库全称",
    prop: "name"
  },
  {
    label: "仓库简称",
    prop: "shortName",
    slot: "shortName"
  },
  {
    label: "相关品种",
    prop: "category",
    slot: "category"
  },
  {
    label: "所在省市",
    prop: "city",
    slot: "city"
  },
  {
    label: "具体地址",
    prop: "address",
    type: "textarea"
  }
];

export default {
  props: {
    value: {
      type: Boolean
    },
    title: {
      type: String
    }
  },
  data() {
    let validateShortName = (rule, value, callback) => {
      let shortNames = this.updateForm.shortNames.filter(i => i.value);
      if (shortNames.length === 0) {
        callback(new Error("请输入仓库简称"));
      }
      callback();
    };
    return {
      updateFormData,
      updateForm: {
        name: undefined,
        shortNames: [
          {
            value: undefined
          }
        ],
        categoryFees: [
          {
            categoryId: [],
            fee: ""
          }
        ],
        city: undefined,
        address: undefined
      },
      updateFormRules: {
        name: [
          { required: true, message: "请输入仓库全称", trigger: "change" }
        ],
        shortName: [
          { required: true, validator: validateShortName, trigger: "change" }
        ],
        city: [{ required: true, message: "请选择省市", trigger: "change" }],
        address: [
          { required: true, message: "请输入具体地址", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    updateVisible: {
      get() {
        return this.value;
      },
      set(v) {
        this.$emit("input", v);
      }
    },
    // 校验相关品种是否填写完整，即一行中品种和转货权要么都不填，要么都填
    validateCorrelationCategory() {
      return (idx, name) => {
        let className = "";
        if (name == "categoryId") {
          if (
            this.updateForm.categoryFees[idx].categoryId.length === 0 &&
            this.updateForm.categoryFees[idx].fee
          ) {
            className = "has-error";
          }
        } else if (name === "fee") {
          if (
            !this.updateForm.categoryFees[idx].fee &&
            this.updateForm.categoryFees[idx].categoryId.length !== 0
          ) {
            className = "has-error";
          }
        }
        return className;
      };
    }
  },
  methods: {
    updateCancel() {
      this.updateForm = {
        name: undefined,
        shortNames: [
          {
            value: undefined
          }
        ],
        categoryFees: [
          {
            categoryId: [],
            fee: ""
          }
        ],
        city: undefined,
        address: undefined
      };
    },
    // 新增一条仓库简称
    addShortName() {
      this.$set(this.updateForm.shortNames, this.updateForm.shortNames.length, {
        value: undefined
      });
    },
    // 删除一条仓库简称
    delShortName(idx) {
      this.updateForm.shortNames.splice(idx, 1);
    },
    // 新增一条相关品种
    addCategory() {
      this.$set(
        this.updateForm.categoryFees,
        this.updateForm.categoryFees.length,
        {
          categoryId: [],
          fee: ""
        }
      );
    },
    // 删除一条相关品种
    delCategory(idx) {
      this.updateForm.categoryFees.splice(idx, 1);
    },
    // 确认提交
    submit() {
      this.$refs.updateForm.validated().then(() => {
        //   查询相关品种是否填写正确
        let hasError = this.$refs.categoryList.getElementsByClassName(
          "has-error"
        );
        if (hasError.length === 0) {
          // 过滤掉没有填写的仓库简称及没有填写完整的相关品种
          let shortNames = JSON.parse(
            JSON.stringify(this.updateForm.shortNames)
          )
            .map(i => i.value)
            .filter(i => i);
          let categoryFees = JSON.parse(
            JSON.stringify(this.updateForm.categoryFees)
          ).filter(i => i.categoryId.length !== 0);
          if (categoryFees.length === 0) {
            categoryFees = undefined;
          } else {
            categoryFees.forEach(item => {
              item.categoryId = item.categoryId[item.categoryId.length - 1];
            });
          }
          addwarehouse({
            name: this.updateForm.name,
            shortName: shortNames,
            categoryFees: categoryFees,
            cityId: this.updateForm.city[1],
            address: this.updateForm.address
          }).then(() => {
            // this.updateVisible = false;
            // this.reload();
            this.$emit("updated");
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.shortNameList {
  li {
    ::v-deep .ant-input {
      width: 200px;
      margin-right: 10px;
    }
  }
}
.categoryList {
  li {
    .c-category {
      width: 200px;
      margin-right: 10px;
    }
    .fee {
      width: 120px;
      margin-right: 10px;
    }
  }
}
</style>
